package com.quxiang.pay.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.quxiang.pay.model.PayCallbackModel;
import com.quxiang.pay.model.PayModel;
import com.quxiang.pay.model.ProductModel;
import com.quxiang.pay.model.ResponseModel;
import com.quxiang.pay.service.PayService;
import com.quxiang.pay.service.WechatService;
import com.quxiang.pay.util.IpUtils;

/**
 * 监控接口 提供运维监控使用 组件服务提供间断后后脚本拉起
 * 
 * @author liulu
 *
 */
@RestController
@RequestMapping("/pay")
public class PayController {

	private static Logger logger = LoggerFactory.getLogger(PayController.class);

	@Autowired
	private PayService payServie;

	@Autowired
	private WechatService weChatService;

	/**
	 * 发起微信请求获取用户信息 授权成功返回商品列表
	 */
	@RequestMapping("/cymj/productList")
	public void getCymjProductList(HttpServletRequest req, HttpServletResponse resp) {

		// 发起微信认证，获取用户信息
		logger.info("cymj 访问商品列表..");
		String authUrl = weChatService.wxCymjAuth();
		if (StringUtils.isNotEmpty(authUrl)) {
			try {
				resp.sendRedirect(authUrl);
			} catch (IOException e) {
				logger.error("wxauth 重定向 error ", e);
			}
		} else {
			logger.warn("wxauth 重定向url为空");
		}

	}

	/**
	 * 发起微信请求获取用户信息 授权成功返回商品列表
	 */
	@RequestMapping("/xunle/productList")
	public void getXunleProductList(HttpServletRequest req, HttpServletResponse resp) {

		// 发起微信认证，获取用户信息
		logger.info("xunle 访问商品列表..");
		String authUrl = weChatService.wxXunLeAuth();
		if (StringUtils.isNotEmpty(authUrl)) {
			try {
				resp.sendRedirect(authUrl);
			} catch (IOException e) {
				logger.error("wxauth 重定向 error ", e);
			}
		} else {
			logger.warn("wxauth 重定向url为空");
		}

	}

	/**
	 * 发起微信请求获取用户信息 授权成功返回商品列表
	 */
	@RequestMapping("/maque/productList")
	public void getMaqueProductList(HttpServletRequest req, HttpServletResponse resp) {

		// 发起微信认证，获取用户信息
		logger.info("maque 访问商品列表..");
		String authUrl = weChatService.wxMaqueAuth();
		if (StringUtils.isNotEmpty(authUrl)) {
			try {
				resp.sendRedirect(authUrl);
			} catch (IOException e) {
				logger.error("wxauth 重定向 error ", e);
			}
		} else {
			logger.warn("wxauth 重定向url为空");
		}

	}

	@RequestMapping("/makePayOrder")
	@ResponseBody
	public ResponseModel<PayModel> makePayOrder(ProductModel product, HttpServletRequest req) {

		logger.info(" make order start...  productType = {} ", product.getProductType());

		long startTime = System.currentTimeMillis();
		ResponseModel<PayModel> response = new ResponseModel<PayModel>();
		String userAgent = req.getHeader("user-agent");
		if (userAgent != null && userAgent.indexOf("MicroMessenger") != -1 && userAgent.indexOf("Mobile") != -1) {

			int result = payServie.checkOrderParams(product, response);
			if (result == 0) {
				String ip = IpUtils.getIPAddr(req);
				try {
					result = payServie.makePayOrder(product, response, ip);
				} catch (Exception e) {
					logger.error("make order error = {}", e);
					response.setInfo(-2, "服务器忙，请稍后再试");
				}
				if (result == 0) {
					logger.info("make order success.. tokenId = {}", response.getData());
				} else {
					logger.info("make order fail.. msg = {}", response.getResultMsg());
				}
			} else {
				logger.info("make order check param error .. msg = {}", response.getResultMsg());
			}

		} else {
			logger.error("make order 不是使用维修客户端 = {}");
			response.setInfo(-2, "请使用微信手机客户端进行支付");
		}
		logger.info(" make order end ... time = {} result = {}", System.currentTimeMillis() - startTime, response);
		return response;

	}

	@RequestMapping("/cymjcallback")
	public String cymjCallback(@RequestBody(required = true) PayCallbackModel payCallback) {

		try {
			int result = payServie.doCallbackCymj(payCallback);
			if (result == 0) {
				return "success";
			} else {
				return "fail";
			}
		} catch (Exception e) {
			return "fail";
		}
	}

	@RequestMapping("/xunlecallback")
	public String xunleCallback(@RequestBody(required = true) PayCallbackModel payCallback) {

		try {
			int result = payServie.doCallbackXunle(payCallback);
			if (result == 0) {
				return "success";
			} else {
				return "fail";
			}
		} catch (Exception e) {
			return "fail";
		}
	}

	@RequestMapping("/maquecallback")
	public String maqueCallback(@RequestBody(required = true) PayCallbackModel payCallback) {

		try {
			int result = payServie.doCallbackMaque(payCallback);
			if (result == 0) {
				return "success";
			} else {
				return "fail";
			}
		} catch (Exception e) {
			return "fail";
		}
	}

	@RequestMapping("/userCancel")
	public String userCancel(int orderId) {

		try {
			int reuslt = payServie.userCancel(orderId);
			if (reuslt == 0) {
				return "sucess";
			} else {
				return "fail";
			}
		} catch (Exception e) {
			logger.error("用户取消支付error = {}", e);
			return "fail";
		}

	}

}
